<template>
<div class="app-container">
  <!--搜索栏和功能按钮-->
  <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"  label-width="68px">
    <el-form-item label="项目编码" prop="subjectCode">
      <el-input
        v-model="queryParams.subjectCode"
        placeholder="请输入项目编码"
        clearable
        @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item label="项目名称" prop="subjectName">
      <el-input
        v-model="queryParams.subjectName"
        placeholder="请输入项目名称"
        clearable
        @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item label="项目类型" prop="subjectType">
      <el-select v-model="queryParams.subjectType" placeholder="项目类型" clearable>
        <el-option
          v-for="dict in dict.type.subject_type"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>
  <el-row :gutter="10" class="mb8">
    <el-col :span="1.5">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
      >新增</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button
        type="success"
        plain
        icon="el-icon-edit"
        size="mini"
        :disabled="single"
        @click="updateIds"
      >修改</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button
        type="danger"
        plain
        icon="el-icon-delete"
        size="mini"
        :disabled="multiple"
        @click="deleteList"
      >删除</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" >导入</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button
        type="warning"
        plain
        icon="el-icon-download"
        size="mini"
        @click="handleExport"
      >导出</el-button>
    </el-col>
<!--    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
  </el-row>
  <!--表格区域-->
  <el-table  :data="subjectList" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column label="项目编码" align="center" prop="subjectCode" />
    <el-table-column label="项目名称" align="center" prop="subjectName" />
    <el-table-column label="项目内容" align="center" prop="subjectContent" />
    <el-table-column label="标准" align="center" prop="subjectStandard" />
<!--    <el-table-column label="项目名称" align="center" prop="subjectName" />-->
    <el-table-column label="项目类型" align="center" prop="subjectType" >
      <template slot-scope="scope">
        <dict-tag :options="dict.type.subject_type" :value="scope.row.subjectType"/>
      </template>
    </el-table-column>
    <el-table-column label="是否是启用" align="center" prop="enableFlag" >
      <template slot-scope="scope">
        <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.enableFlag"/>
      </template>
    </el-table-column>
    <el-table-column label="备注" align="center" prop="remark" />
    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
      <template slot-scope="scope">
        <el-button
          size="mini"
          type="text"
          icon="el-icon-edit"
          @click="handleUpdate(scope.row)"
        >修改</el-button>
        <el-button
          size="mini"
          type="text"
          icon="el-icon-delete"
          @click="handleDelete(scope.row)"
        >删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--增加,修改页面-->
  <el-dialog :title="title" :visible.sync="open" width="700px">
    <el-form :model="form" ref="form" label-width="12px">
    <el-row>
      <el-col :span="12">
        <el-form-item label="项目编码" label-width="120px">
          <el-input v-model="form.subjectCode" autocomplete="off"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="项目名称" label-width="120px">
          <el-input v-model="form.subjectName" autocomplete="off"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目类型" label-width="120px">
            <el-radio-group v-model="form.subjectType" >
              <el-radio
                v-for="dict in dict.type.subject_type"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用" label-width="120px">
            <el-radio-group v-model="form.enableFlag" >
              <el-radio
                v-for="dict in dict.type.sys_yes_no"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目内容" label-width="120px">
            <el-input type="textarea" v-model="form.subjectContent" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="标准" label-width="120px">
            <el-input type="textarea" v-model="form.subjectStandard" autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit">确 定</el-button>
      <el-button  @click="cancel">取消</el-button>
    </div>
  </el-dialog>

  <!-- 点检保养项目导入对话框 -->
  <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
    <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip text-center" slot="tip">
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
        </div>
        <span>仅允许导入xls、xlsx格式文件。</span>
        <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
      </div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitFileForm">确 定</el-button>
      <el-button @click="upload.open = false">取 消</el-button>
    </div>
  </el-dialog>
  <!--分页区域-->
  <pagination
    v-show="total>0"
    :total="total"
    :page.sync="queryParams.pageNum"
    :limit.sync="queryParams.pageSize"
    @pagination="getList"
  />

  <div id="chart" style="width: 600px; height: 400px;"></div>
</div>

</template>

<script>
import {
  addSubject,
  deleteList,
  deleteSubject,
  getLogEcharts,
  getSubjectById,
  listSubject,
  updateSubject
} from "@/api/dv/subject";
import {getToken} from "@/utils/auth";
import * as echarts from 'echarts'

export default {
  name: "Subject",
  dicts: ['subject_type','sys_yes_no'],
  data() {
    return {
      // 点检保养项目导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/dv/subject/importData"
      },
      form:{},
      open:false,
      title:null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        subjectCode: null,
        subjectName: null,
        subjectType: null
      },
      //loading:true,
      subjectList:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids:[],
      // 总条数
      total: 0,
    }
  },
  mounted() {
    this.initChart()
  },
  methods: {
    initChart() {
      // 2初始化
      const myChart = echarts.init(document.getElementById('chart'))
      var option = {
        title: {
          text: '最近7天登录次数'
        },
        tooltip: {
        },
        legend: {
          data: ['次数']
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [],
            type: 'line'
          }
        ]
      };
      // 4使用图表配置
      myChart.setOption(option)

      // 发请求 获取数据
      getLogEcharts().then(res => {
        // 后台返回的是'2025-10-01',需要展示成'10-01'
        let xArr = [];
        res.data.xAxisData.forEach(item => {
          xArr.push(item.substring(5))
        })

        // 填入数据
        myChart.setOption({
          xAxis: {
            data: xArr
          },
          series: [
            {
              name: '次数',
              data: res.data.seriesData
            }
          ]
        });
      })
    },
    // 提交上传文件
    submitFileForm() {
      const file = this.$refs.upload.uploadFiles
      if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
        return
      }
      this.$refs.upload.submit()
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dv/subject/export', {
        ...this.queryParams
      }, `点检保养项目_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "点检保养项目导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
      importTemplate() {
      this.download('dv/subject/importTemplate', {
      }, `点检保养项目模板_${new Date().getTime()}.xlsx`)
    },
    deleteList(){
      const subjectId = this.ids.join(',')
      console.log(subjectId)
      deleteList(subjectId).then(res=>{
        this.$modal.msgSuccess("删除成功")
        this.getList()
      })
    },
    handleDelete(row){
      const subjectId = row.subjectId
      deleteSubject(subjectId).then(res=>{
        this.$modal.msgSuccess("删除成功")
        this.getList()
      })
    },
    updateIds(){
      const subjectId = this.ids.join()
      console.log()
      getSubjectById(subjectId).then(res=>{
        this.form = res.data
        this.open = true
        this.title = "修改项目"
      })
    },
    //修改
    handleUpdate(row){
      this.open = true
      this.title = '修改项目'
      this.form = row
    },
    cancel(){
      this.form.subjectId=null
      this.form.subjectCode = null
      this.form.subjectName = null
      this.form.subjectType = null
      this.form.enableFlag = null
      this.form.subjectContent = null
      this.form.subjectStandard = null
      this.open = false
    },
    handleAdd(){
      this.open = true
      this.title = '新增项目'
    },
    //提交修改或增加
    submit(){
      if(this.title == "新增项目"){
        addSubject(this.form).then(res=>{
          this.$modal.msgSuccess("新增成功")
          this.open=false
          this.cancel()
          this.getList()
        })
      }
      if(this.title == "修改项目"){
        updateSubject(this.form).then(res=>{
          this.$modal.msgSuccess("修改成功")
          this.open=false
          this.getList()
        })
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.subjectId)
      console.log(this.ids)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    handleQuery(){
      this.getList();
    },
    resetQuery(){
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        subjectCode: null,
        subjectName: null,
        subjectType: null
      }
      this.getList();
    },
    getList(){
      listSubject(this.queryParams).then(res => {
        this.subjectList = res.rows
        console.log(this.subjectList)
        this.total = res.total
        this.loading = false
      })
    }
  },
  created() {
    this.getList();
  }
}
</script>

<style scoped lang="scss">

</style>
